export default class CommandHandler {
    static resolveCommand(data: Buffer, cmd: string, callback:(args: number[]) => void): void{
        let commandLength = data.readUInt8(0);
        let command:string = data.slice(1, commandLength+1).toString();
        if(command == cmd)
        {
            //let args:number[] = data.readUInt16LE(5);
            let args:number[] = new Array<number>();
            let ancIndex = commandLength + 1;
            let step = 4;
            for(let i = 1;; i++)
            {
                let startPos = ancIndex+step*(i-1);
                if(startPos == data.length) break;
                args.push(data.readInt32LE(startPos));
            }
            callback(args);
        }
    }

    static packageCommand(cmd: string, arg?: number[]): Buffer {
        let bufferlength = 0;

        bufferlength += cmd.length;
        if(arg != undefined)
        {
            bufferlength += arg.length * 4;
        }
        bufferlength += 1; //这个字节存放命令长度

        let dataS:Buffer = Buffer.alloc(bufferlength);

        dataS.writeUInt8(cmd.length, 0);
        dataS.write(cmd, 1, "ascii");

        let lastWriteIndex = cmd.length + 1;
        for(let i in arg)
        {
            dataS.writeUInt32LE(arg[i], lastWriteIndex);
            lastWriteIndex += 4;
        }

        return dataS;
    }
}